//
//  MenuDetailsViewController.m
//  Cooking
//
//  Created by dllo on 15/8/25.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "MenuDetailsViewController.h"
#import "AppMacro.h"
#import "MenuDetailsCollectionViewCell.h"
#import "AsyncGetConnection.h"
#import "FoodDetailsModel.h"
#import "CookViewController.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"

@interface MenuDetailsViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, MBProgressHUDDelegate>

@property (retain, nonatomic) NSMutableArray   *collectionArray;
@property (retain, nonatomic) UICollectionView *detailsMenu;
@property (retain, nonatomic) MBProgressHUD    *HUD;
@property (assign, nonatomic) NSInteger        page;

@end

@implementation MenuDetailsViewController

- (void)dealloc {
    [_collectionArray release];
    [_detailsMenu release];
    [_HUD release];
    [_typeId release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectionArray = [NSMutableArray array];
        self.page = 1;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    //    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}
#pragma mark -
#pragma mark 左侧返回键
- (void)leftButtonAction:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 255.0 green:125 / 255.0 blue:67 / 255.0 alpha:1];
    
    //左返回键
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhuianniu"] style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self createDetailsCollectionView];
    [self beginConnect];

 
#pragma mark -
#pragma 下拉刷新
    [_detailsMenu addHeaderWithCallback:^{
        
        [AsyncGetConnection asyncGetConnectionWithURL:[NSString stringWithFormat:@"http://121.40.54.242:80/HandheldKitchen/api/found/tblBoutique!getTblBoutiqueVegetableList.do?is_traditional=0&page=1&pageRecord=10&phonetype=0&user_id=0&typeId=%@", self.typeId] parameters:nil block:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.title = [dic objectForKey:@"title"];
            NSArray *array = [dic objectForKey:@"data"];
            [_collectionArray removeAllObjects];
            for (NSDictionary *value in array) {
                FoodDetailsModel *foodDetailsModel = [[FoodDetailsModel alloc] init];
                [foodDetailsModel setValuesForKeysWithDictionary:value];
                [_collectionArray addObject:foodDetailsModel];
                [foodDetailsModel release];
            }
            
            [_detailsMenu reloadData];
            [_detailsMenu headerEndRefreshing];
        }];
    }];
    
#pragma mark -
#pragma 上拉加载
    [_detailsMenu addFooterWithCallback:^{
        
        _page = _page + 1;
        [AsyncGetConnection asyncGetConnectionWithURL:[NSString stringWithFormat:@"http://121.40.54.242:80/HandheldKitchen/api/found/tblBoutique!getTblBoutiqueVegetableList.do?is_traditional=0&page=%ld&pageRecord=10&phonetype=0&user_id=0&typeId=%@", _page, self.typeId] parameters:nil block:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.title = [dic objectForKey:@"title"];
            NSArray *array = [dic objectForKey:@"data"];
            for (NSDictionary *value in array) {
                FoodDetailsModel *foodDetailsModel = [[FoodDetailsModel alloc] init];
                [foodDetailsModel setValuesForKeysWithDictionary:value];
                [_collectionArray addObject:foodDetailsModel];
                [foodDetailsModel release];
            }
            //网络解析的时候自动刷新一下数据
            [_detailsMenu reloadData];
            [_detailsMenu footerEndRefreshing];
        }];
    }];
}
#pragma mark -
#pragma 网络数据解析
- (void)beginConnect {
    
    [AsyncGetConnection asyncGetConnectionWithURL:[NSString stringWithFormat:@"http://121.40.54.242:80/HandheldKitchen/api/found/tblBoutique!getTblBoutiqueVegetableList.do?is_traditional=0&page=1&pageRecord=10&phonetype=0&user_id=0&typeId=%@", self.typeId] parameters:nil block:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.title = [dic objectForKey:@"title"];
        NSArray *array = [dic objectForKey:@"data"];
//        [_collectionArray removeAllObjects];
        for (NSDictionary *value in array) {
            FoodDetailsModel *foodDetailsModel = [[FoodDetailsModel alloc] init];
            [foodDetailsModel setValuesForKeysWithDictionary:value];
            [_collectionArray addObject:foodDetailsModel];
            [foodDetailsModel release];
        }
        //网络解析的时候自动刷新一下
        [_detailsMenu headerBeginRefreshing];
        [_detailsMenu reloadData];
        [_HUD hide:YES];
    }];
}

- (void)createDetailsCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH / 2 - 15 , 126);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.detailsMenu = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    _detailsMenu.delegate = self;
    _detailsMenu.dataSource = self;
    _detailsMenu.backgroundColor = [UIColor whiteColor];
    [_detailsMenu registerClass:[MenuDetailsCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.view addSubview:_detailsMenu];
    [flowLayout release];
    [_detailsMenu release];
    
    
    //加载等待
    self.HUD = [[MBProgressHUD alloc] init];
    _HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
    _HUD.delegate = self;
    _HUD.backgroundColor = [UIColor clearColor];
    _HUD.detailsLabelText = @"努力加载中...";
    _HUD.dimBackground = YES;
}

#pragma mark -
#pragma mark detailsCollectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _collectionArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MenuDetailsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor redColor];
    FoodDetailsModel *foodDetailsModel = [_collectionArray objectAtIndex:indexPath.item];
    [cell sendValueWithModel:foodDetailsModel];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CookViewController *cookVC = [[CookViewController alloc] init];
    cookVC.myID = [[_collectionArray objectAtIndex:indexPath.item] valueForKey:@"vegetable_id"];
    cookVC.nameStr = [[_collectionArray objectAtIndex:indexPath.item] valueForKey:@"name"];
    //收藏传值
    RecommendModel *recommend = [_collectionArray objectAtIndex:indexPath.item];
    cookVC.recommendModel = recommend;
    [self.navigationController pushViewController:cookVC animated:YES];
    [cookVC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
